package com.talent.carrot.B_workqueues;

import com.rabbitmq.client.*;
import org.yaml.snakeyaml.Yaml;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * 躲了一辈子雨，雨会不会很难过。
 * </p>
 * Created by zhumenglong on 2017/6/11.
 */
public class Task {

    //队列名称
    private final static String QUEUE_NAME = "workqueue-durable";

    private static InputStream rabbitConfig;

    private static Map configMap;

    static {
        rabbitConfig = Task.class.getClassLoader().getResourceAsStream("RabbitMqConfig.yaml");
    }


    public static void main(String[] args) throws IOException, TimeoutException {
        Yaml yaml = new Yaml();
        configMap = (HashMap<String, String>) yaml.load(rabbitConfig);

        //区分不同工作进程的输出
        int hashCode = Work.class.hashCode();

        //创建连接和频道
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost((String) configMap.get("CF.Host"));
        //指定用户 密码
        factory.setUsername((String) configMap.get("CF.Username"));
        factory.setPassword((String) configMap.get("CF.Password"));
        //指定端口
        factory.setPort(AMQP.PROTOCOL.PORT);
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        boolean durable = true; //设置消息持久化  RabbitMQ不允许使用不同的参数重新定义一个队列，所以已经存在的队列，我们无法修改其属性。

        //声明队列
        channel.queueDeclare(QUEUE_NAME, durable, false, false, null);

        //发送10条消息，依次在消息后面附加1-10个点
        for (int i = 5; i > 0; i--) {
            String dots = "";
            for (int j = 0; j <= i; j++) {
                dots += ".";
            }
            String message = "helloworld" + dots + dots.length();
            //MessageProperties.PERSISTENT_TEXT_PLAIN 标识我们的信息为持久化的
            channel.basicPublish("", QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
            System.out.println("Sent Message：'" + message + "'");
        }
        //关闭频道和资源
        channel.close();
        connection.close();
    }

    /**
     * 每个点耗时1s
     *
     * @param task
     * @throws InterruptedException
     */
    private static void doWork(String task) throws InterruptedException {
        for (char ch : task.toCharArray()) {
            if (ch == '.')
                Thread.sleep(1000);
        }
    }
}
